<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8"/>
    <meta name="Generator" content="EditPlus®">
    <meta name="Author" content="ZhangBin">
    <meta name="Keywords" content="">
    <meta name="Description" content="">
    <title>fileinput实现文件上传</title>
    <link rel="shortcut icon" href="/static/img/Head.png" type="image/x-icon"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/plugins/fileinput-4.1.9/css/fileinput.min.css"/>
    <style type="text/css">
        #file_1 {
            width: 150px;
        }

        h2 {
            text-align: center;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
<h2>仅仅是演示文件上传，请不要上传贵重资料！</h2>
<div class="container">
    <form enctype="multipart/form-data" method="post">
        <div>
            <!--class='file' 是fileinput.js中设置的type='file'升级版-->
            <input id="file_1" class="file" type="file" name="files" multiple data-min-file-count="1"/>
        </div>
    </form>
    <table id="uploadFIleSrc" class="table table-striped">
        <caption>以上传的文件</caption>
        <thead>
        <tr>
            <th>序号</th>
            <th>名称</th>
            <th>上传时间</th>
            <th>大小（kb）</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr class="lastTr">
            <td>统计：</td>
            <td></td>
            <td></td>
            <td class="size">0</td>
            <td></td>
        </tr>
        </tbody>
    </table>
</div>
<script type="text/javascript" src="/static/plugins/jQuery/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/static/plugins/fileinput-4.1.9/fileinput.min.js"></script><!--必须在jquery之后加载-->
<script type="text/javascript" src="/static/plugins/fileinput-4.1.9/locales/fileinput_locale_zh.js"></script>
<!--将fileinput.js转换为中文显示-->

<script type="text/javascript">
    $(function () {
        $("#uploadFIleSrc").on("click", ".btn-success", function () {
            var path = $(this).attr("data-path");
            window.open(path);
        })
    })
    $.ajax({
        url: "/demo/fileInputUpload/getUploadFile.zb",
        dataType: "JSON",
        type: "POST"
    }).done(function (res) {
        if (res && res.length > 0) {
            for (var i = 0; i < res.length; i++) {
                var index = $("#uploadFIleSrc tbody tr").length;
                var tr = "<tr>" +
                    "<td>" + index + "</td>" +
                    "<td>" + res[i].fileName + "</td>" +
                    "<td>" + res[i].uploadDate + "</td>" +
                    "<td>" + res[i].size + "</td>" +
                    "<td><button class='btn-success' data-path='" + res[i].path + "'>下载</button></td>" +
                    "</tr>";
                $("#uploadFIleSrc").prepend($(tr));
            }
            getTotal();
        }
    })
    $("#file_1").fileinput({
        //设置一个上传url
        uploadUrl: '/demo/fileInputUpload/upload.zb',
        //允许上传的文件类型
        allowedFileTypes: ['image', 'video', 'excel'],
        //类型扩展 有限allowedFileTypes
        allowedFileExtensions: ["jpg", "png", "gif", "xls", "xlsx", "doc", "docx", "zip", "rar", "txt"],
        //允许什么类型的文件可预览。默认是['image', 'html', 'text', 'video', 'audio', 'flash','object']
        allowedPreviewTypes: ['image', 'text'],
        //allowedPreviewTypes:false,//不预览任何类型的文件(不会显示预览窗口)
        /*previewSettings: {
            image: {height: "100px"},//设置预览文件的显示大小
        },*/
        maxFileSize: 10 * 1024,//允许上传文件的大小，（单位：KB），包括扩展类型文件的限制
        minFileCount: 1,//上传的最小文件数
        maxFileCount: 5, //表示允许同时上传的最大文件个数
        showUpload: true,//是否显示上传按钮
        showCaption: true,//是否显示标题
        browseClass: "btn btn-primary",//按钮样式
        showPreview: true,//是否显示预览
        showRemove: true,//是否显示移除按钮
        showCancel: true,//是否显示取消按钮
        uploadExtraData: {id: Math.random()}
    });
    //上传成功的回调函数
    $("#file_1").on("fileuploaded", function (event, data, previewId, index) {
        var index = $("#uploadFIleSrc tbody tr").length;
        if (data.response) {
            var path = data.response.path;
            var fileName = path.substring(path.lastIndexOf("/") + 1);
            var size = data.response.size;
            var uploadDate = data.response.uploadDate;
            var tr = "<tr>" +
                "<td>" + index + "</td>" +
                "<td>" + fileName + "</td>" +
                "<td>" + uploadDate + "</td>" +
                "<td>" + size + "</td>" +
                "<td><button class='btn-success' data-path='" + path + "'>下载</button></td>" +
                "</tr>";
            $("#uploadFIleSrc").prepend($(tr));
            getTotal();
        }
    })

    function getTotal() {
        var trs = $("tbody tr");
        if (trs.length < 2) {
            return false;
        }
        var totalSize = 0;
        for (var i = 0; i < trs.length - 1; i++) {
            var td = trs.eq(i).find("td").eq(3).text();
            totalSize += (td - 0);
        }
        var mb = totalSize > 1024 ? toDecimal2(totalSize / 1024) + "Mb" : totalSize + "Kb";
        $("tr.lastTr td.size").text(mb);
    }

    function toDecimal2(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return false;
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return s;
    }
</script>
</body>
</html>
